const express = require("express");
const { nextTick } = require("process");
//引入mysql模块
const pool = require("../pool");
//创建路由器对象
const u = express.Router();
//添加路由
// 用户注册接口(post /reg)
// 接口地址：http://127.0.0.1:3000/v1/users/reg
// 请求方式：post
u.post("/reg", (req, res, next) => {
  // 1.获取post传递的参数
  var obj = req.body;
  console.log(obj);
  //1.2验证手机格式是否正确,同时阻止后面代码执行 return
  var reg = /^1[35789]\d{9}$/.test(req.body.phone);
  if (!reg) {
    res.send({ code: 405, msg: "手机格式错误" });
    return;
  }
  //   1.3判断邮箱格式,同时阻止后面代码执行 return
  var email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(
    req.body.email
  );
  if (!email) {
    res.send({ code: 405, msg: "邮箱格式错误" });
    return;
  }
  //console.log(obj);//测试是否获取到参数
  // 2.使用SQL命令把数据插入到数据表
  pool.query("insert into xz_user set?", [obj], (err, r) => {
    if (err) {
      //throw 抛出错误，阻止后边程序执行，用于调试
      //throw err;
      //交给下一个错误处理中间件
      next(err);
      //阻止往后执行 函数里用return
      return;
    }
    console.log(r);
    // res.send({})
    res.send({ code: 200, msg: "注册成功" });
  });
});
//添加删除接口(delete /:编号)  接收传递的编号，执行SQL命令,成功{code:200,msg:'删除成功'} 失败{code:500,msg:'删除失败'}   加前缀
//接口地址 http://127.0.0.1:3000/v1/users/deletes/4
u.delete("/deletes/:id", (req, res, next) => {
  console.log(req.params);
  pool.query("delete from xz_user where uid=?", [req.params.id], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    console.log(r);
    if (r.affectedRows != 0) {
      res.send({ code: 200, msg: "删除成功" });
    } else {
      res.send({ code: 500, msg: "删除失败" });
    }
  });
});
//添加登录接口(post /login)接收用户名和密码，执行SQL命令，查询数据库中是否有该用户 {code:200,msg:'登录成功'} 失败{code:500,msg:'登录失败'}
u.post("/login", (req, res, next) => {
  console.log(req.body);
  //用户名不为空
  if (!req.body.uname) {
    res.send({ code: 401, msg: "用户名不能为空" });
    return;
  }
  pool.query(
    "select * from xz_user where uname=? && upwd=?",
    [req.body.uname, req.body.upwd],
    (err, r) => {
      if (err) {
        next(err);
        return;
      }
      console.log(r);
      //如果结果是空数组说明登录失败
      if (r.length != 0) {
        res.send({ code: 200, msg: "登录成功" });
      } else {
        res.send({ code: 500, msg: "登录失败" });
      }
    }
  );
});
//添加修改用户资料接口(put /),传递(修改条件-编号，邮箱、手机、真实姓名、性别)执行SQL命令  {code:200,msg:'修改成功'} 失败{code:500,msg:'修改失败'}
u.put("/", (req, res, next) => {
  console.log(req.body);
  pool.query(
    "update xz_user set ? where uid=?",
    [req.body, req.body.uid],
    (err, r) => {
      if (err) {
        next(err);
        return;
      }
      console.log(r);
      if (r.affectedRows != 0) {
        res.send({ code: 200, msg: "修改成功" });
      } else {
        res.send({ code: 500, msg: "修改失败" });
      }
    }
  );
});

//暴露路由
module.exports = u;
